package com.ruoyi.workflow.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.workflow.domain.CarPackageAudit;
import com.ruoyi.workflow.domain.vo.CarPackageAuditVo;
import com.ruoyi.workflow.domain.vo.HistoricActivity;
import com.ruoyi.workflow.service.ICarPackageAuditService;
import com.ruoyi.workflow.service.IDefinitionNodeService;
import com.ruoyi.workflow.service.IDoneTaskService;
import com.ruoyi.workflow.service.ITodoTaskService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * {@code @name} TodoTaskServiceImpl
 *
 * @author god磊
 * @since 2022/11/20 13:58
 **/
@Service
public class DoneTaskServiceImpl implements IDoneTaskService {
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IDefinitionNodeService definitionNodeService;
    @Autowired
    private HistoryService historyService;
    @Override
    public TableDataInfo selectTodoList(CarPackageAudit carPackageAudit) {
        // 1. 创建返回分页数据对象
        TableDataInfo info = new TableDataInfo();
        info.setCode(HttpStatus.SUCCESS);
        info.setMsg("查询成功");

        // 2. 获取当前登录用户的 id
        String username = SecurityUtils.getUsername();
        // 3. 基于当前登录用户, 去查询该用户为候选人/负责人的任务数量
        long total = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(username)
                .count();
        info.setTotal(total);

        // 4. 如果数量为 0, 直接返回空数据
        if (total == 0) {
            info.setRows(Collections.emptyList());
            return info;
        }

        // 1. 接收前端的分页条件
        PageDomain pageDomain = TableSupport.buildPageRequest();
        // 计算分页开始索引位置 (当前页 - 1) * 每页显示数量
        int startIndex = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();

        // 5. 基于当前登录用户去查询已完成的任务
        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(username)
                .finished()
                .orderByTaskCreateTime()
                .desc()
                .listPage(startIndex, pageDomain.getPageSize());
        List<CarPackageAudit> list = new ArrayList<>();
        // 6. 遍历任务列表
        for (HistoricTaskInstance task : taskList) {
            // 7. 获取该任务的流程实例 id, 查询流程实例对象, 得到业务标识
            HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            String businessKey = instance.getBusinessKey();
            // 8. 通过业务标识, 查询审核记录对象
            CarPackageAudit audit = carPackageAuditService.getById(Long.valueOf(businessKey));
            // 实际需要的对象
            CarPackageAuditVo vo = new CarPackageAuditVo();
            // 将 audit 中所有同名属性 copy 到 vo 对象
            BeanUtils.copyBeanProp(vo, audit);

            // 查询创建人
            SysUser sysUser = userService.selectUserById(Long.parseLong(audit.getCreatorId()));
            vo.setCreatorName(sysUser.getNickName());

            // 9. 为审核记录设置当前任务名称/id, 当前审核人,完成时间
            vo.setFinishedTime(task.getEndTime());
            vo.setTaskId(task.getId());
            vo.setTaskName(task.getName());
            vo.setAuditors(SecurityUtils.getUsername());
            // 10. 将当前审核记录对象放入返回的集合中
            list.add(vo);
        }
        // 11. 最终返回审核记录列表集合
        info.setRows(list);
        return info;
    }

    @Override
    public List<HistoricActivity> selectHistoryList(String instanceId) {
        // 1. 基于流程实例id查询到历史任务(已完成)列表
        List<HistoricActivityInstance> instanceList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(instanceId) // 流程实例 id 查询
                .activityType("userTask") // 按照活动类型为 userTask
                .orderByHistoricActivityInstanceStartTime() // 按照开始时间排序
                .asc() // 升序排序
                .list(); // 返回列表

        // 2. 遍历历史任务集合, 基于任务id查询批注信息
        List<HistoricActivity> list = new ArrayList<>(instanceList.size());
        for (HistoricActivityInstance instance : instanceList) {
            HistoricActivity activity = new HistoricActivity();
            BeanUtils.copyBeanProp(activity, instance); // 将查出来的数据拷贝到自己的活动对象中

            // 批注信息
            List<Comment> comments = taskService.getTaskComments(instance.getTaskId(), "comment");
            if (!CollectionUtils.isEmpty(comments)) {
                activity.setComment(comments.get(0).getFullMessage()); // 获取批注信息
            }

            // 负责人名称
            SysUser user = userService.selectUserByUserName(instance.getAssignee());
            if (user != null) {
                activity.setAssigneeName(user.getNickName());
            }

            // 将创建的对象加入最终返回的 list 中
            list.add(activity);
        }
        // 3. 将批注信息保存到对象, 最终返回数据
        return list;
    }
}